/*
 * Copyright (C) 2008 TranceCode Software
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 *
 * $Id$
 */
package org.trancecode.rdf.base;

import org.trancecode.io.Uris;
import org.trancecode.rdf.AbstractUriReference;
import org.trancecode.rdf.UriReference;
import org.trancecode.rdf.UriReferenceFactory;

import java.net.URI;

import com.google.common.base.Preconditions;


/**
 * Base {@link UriReference} implementation.
 * 
 * @author Herve Quiroz
 * @version $Revision: 3842 $
 */
public final class ImmutableUriReference extends AbstractUriReference
{
	private final String stringValue;
	private URI uri;
	private int hashCode;


	private ImmutableUriReference(final String stringValue)
	{
		this(stringValue, null);
	}


	private ImmutableUriReference(final URI uri)
	{
		this(uri.toString(), uri);
	}


	private ImmutableUriReference(final String stringValue, final URI uri)
	{
		Preconditions.checkNotNull(stringValue);
		Preconditions.checkArgument(!stringValue.isEmpty());
		this.stringValue = stringValue;
		assert Uris.isValidUri(stringValue);
		this.uri = uri;
	}


	@Override
	public String stringValue()
	{
		return stringValue;
	}


	@Override
	public URI uri()
	{
		if (uri != null)
		{
			uri = URI.create(stringValue);
		}

		return uri;
	}


	@Override
	public int hashCode()
	{
		if (hashCode == 0)
		{
			hashCode = super.hashCode();
		}

		return hashCode;
	}


	public static UriReferenceFactory factory()
	{
		return ImmutableUriReferenceFactory.INSTANCE;
	}


	private static class ImmutableUriReferenceFactory implements UriReferenceFactory
	{
		public static final ImmutableUriReferenceFactory INSTANCE = new ImmutableUriReferenceFactory();


		private ImmutableUriReferenceFactory()
		{
			// Singleton
		}


		@Override
		public UriReference newUriReference(final String stringValue)
		{
			return new ImmutableUriReference(stringValue);
		}


		@Override
		public UriReference newUriReference(final URI uri)
		{
			return new ImmutableUriReference(uri);
		}
	}
}
